package com.atguigu.day01;

import com.atguigu.utils.IntSource;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

public class Example7 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .addSource(new IntSource())
                .map(r -> Tuple2.of(r, r))
                .returns(Types.TUPLE(Types.INT, Types.INT))
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {
                        return Tuple2.of(
                                value1.f0 < value2.f0 ? value1.f0 : value2.f0,
                                value1.f1 > value2.f1 ? value1.f1 : value2.f1
                        );
                    }
                })
                .map(new MapFunction<Tuple2<Integer, Integer>, String>() {
                    @Override
                    public String map(Tuple2<Integer, Integer> value) throws Exception {
                        return "最小值：" + value.f0 + ";最大值：" + value.f1;
                    }
                })
                .print();

        env
                .addSource(new IntSource())
                .map(r -> Tuple2.of(r, 1))
                .returns(Types.TUPLE(Types.INT, Types.INT))
                .keyBy(r -> 1)
                .reduce(new ReduceFunction<Tuple2<Integer, Integer>>() {
                    @Override
                    public Tuple2<Integer, Integer> reduce(Tuple2<Integer, Integer> value1, Tuple2<Integer, Integer> value2) throws Exception {
                        return Tuple2.of(value1.f0 + value2.f0, value1.f1 + value2.f1);
                    }
                })
                .map(new MapFunction<Tuple2<Integer, Integer>, Integer>() {
                    @Override
                    public Integer map(Tuple2<Integer, Integer> value) throws Exception {
                        return value.f0 / value.f1;
                    }
                })
                .map(new MapFunction<Integer, String>() {
                    @Override
                    public String map(Integer value) throws Exception {
                        return "平均值是：" + value;
                    }
                })
                .print();

        env.execute();
    }
}
